package com.qch.rocketmq.springboot_ms_rocketmq.service;

import com.qch.rocketmq.springboot_ms_rocketmq.cache.RedisService;
import com.qch.rocketmq.springboot_ms_rocketmq.pojo.GoodDO;
import com.qch.rocketmq.springboot_ms_rocketmq.pojo.OrderDO;
import com.qch.rocketmq.springboot_ms_rocketmq.repositry.GoodsRepository;
import com.qch.rocketmq.springboot_ms_rocketmq.repositry.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author qch
 * @Date 2021/6/23
 */
@Slf4j
@Service
public class OrderService {
    @Autowired
    private GoodsRepository goodsRepository;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OrderRepository orderRepository;
    public OrderDO findByOrderId(String orderId) {
        OrderDO orderDO = new OrderDO();
        orderDO.setOrderNo(orderId);
        Example<OrderDO> example = Example.of(orderDO);
        List<OrderDO> list = orderRepository.findAll(example);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }
    public void save(OrderDO orderDO) {
        orderDO.setCreateTime(new Date());
        orderRepository.save(orderDO);
    }

    public void passTimeProcess(Integer limitTime) {
        OrderDO orderReq = new OrderDO();
        orderReq.setStatus(0);
        Example<OrderDO> example = Example.of(orderReq);
        List<OrderDO> list = orderRepository.findAll(example);
        long now = System.currentTimeMillis();
        if (!list.isEmpty()) {
            for (OrderDO orderDO : list) {
                if((orderDO.getCreateTime().getTime()+limitTime*1000)<=now)
                {
                    orderDO.setStatus(2);
                    orderRepository.save(orderDO);
                    Optional<GoodDO> byId = goodsRepository.findById(orderDO.getGoodId());
                    if(byId.isPresent())
                    {
                        GoodDO goodDO = byId.get();
                        goodDO.setReserveNum(goodDO.getReserveNum()+1);
                        goodsRepository.save(goodDO);
                        redisService.setValue("goods:" + goodDO.getId(), goodDO, 60);
                    }
                }
            }
        }
    }
}
